package com.example.ivideo_2211a

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.common.mvi.BaseViewActivity
import com.example.ivideo_2211a.adapter.DanmuAdapter
import com.example.ivideo_2211a.commodity.CommondityAdapter
import com.example.ivideo_2211a.commodity.CommondityEntity
import com.example.ivideo_2211a.commodity.CommondityRetrorfit
import com.example.ivideo_2211a.databinding.ActivityStartLiveBinding
import com.example.ivideo_2211a.model.DanmuMessage
import com.example.ivideo_2211a.utils.LiveBroadcastUtils
import com.tencent.rtmp.TXLivePushConfig
import com.tencent.rtmp.TXLivePusher
import com.tencent.rtmp.ui.TXCloudVideoView
import kotlinx.coroutines.launch


@Route(path = "/app/StartLiveActivity")
class StartLiveActivity : BaseViewActivity<ActivityStartLiveBinding>() {
    private lateinit var commondityAdapter: CommondityAdapter

    companion object {
        private const val NOTIFICATION_PERMISSION_REQUEST_CODE = 1001
    }
    
    // 弹幕相关
    private lateinit var danmuAdapter: DanmuAdapter
    private var currentUsername = "主播" // 当前用户名，可以从用户信息获取

    override fun getLayoutId(): Int =R.layout.activity_start_live


    override fun setupViews() {
        // 检查并请求通知权限
        checkAndRequestNotificationPermission()

        // 初始化弹幕列表
        initDanmuList()

        // 初始化点击事件
        initClickListeners()

        val mLivePushConfig = TXLivePushConfig()
        val mLivePusher = TXLivePusher(this)
// 一般情况下不需要修改 config 的默认配置
        mLivePusher.config=mLivePushConfig

        //启动本地摄像头预览
        mLivePusher.startCameraPreview(binding.pusherTxCloudView)
        
        // 发送直播预播提醒广播
        sendLiveNotification()

        // 添加一些示例弹幕
        addSampleDanmu()

        //一般不按，就结束就行    因为点击就直接开始直播了
//        binding.start.setOnClickListener {
//
//            val rtmpURL = "rtmp://218953.push.tlivecloud.com/live/sssss?txSecret=f28e75bf0a68398114764d2aced21238&txTime=68A95BCA" //此处填写您的 rtmp 推流地址
//            val ret = mLivePusher.startPusher(rtmpURL.trim { it <= ' ' })
//            if (ret == -5) {
//                Log.i("TAG", "startRTMPPush: license 校验失败")
////            }
//            }
//
//        }



        binding.btnEndLive.setOnClickListener {

            mLivePusher.stopPusher();
            mLivePusher.stopCameraPreview(true); //如果已经启动了摄像头预览，请在结束推流时将其关闭。
            finish()

        }
     mLivePusher.setBeautyFilter(2,8,8,8)
        binding.commondityConBack.setOnClickListener {
            binding.commondityCon.visibility=View.GONE
        }
        binding.btnShoppingCart.setOnClickListener {
            binding.commondityCon.visibility=View.VISIBLE
            //开启携程

            lifecycleScope.launch {
                val commodityList = CommondityRetrorfit.commodityApi.getCommodityList()
                commondityAdapter = CommondityAdapter(commodityList.data)
                binding.commondityConRc.layoutManager= LinearLayoutManager(this@StartLiveActivity)
                binding.commondityConRc.adapter=commondityAdapter
                commondityAdapter.setOnItemClickListener(object :CommondityAdapter.OnItemClickListener{
                    override fun onItemClick(data: CommondityEntity) {
                        // 商品点击事件已在适配器中处理跳转，这里可以添加其他逻辑
                        binding.commondityCon.visibility = View.GONE // 隐藏商品列表
                        //跳转商品详情
                        ARouter.getInstance().build("/app/GoodsDetailActivity")
                            .withString("goodsId", data.id.toString())
                            .navigation()
                        Log.d("goodsId", "onItemClick: "+data.id.toString())
                    }

                })
            }
        }

    }
    
    /**
     * 检查并请求通知权限
     */
    private fun checkAndRequestNotificationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) 
                != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, 
                    arrayOf(Manifest.permission.POST_NOTIFICATIONS), 
                    NOTIFICATION_PERMISSION_REQUEST_CODE)
            }
        }
    }
    
    /**
     * 发送直播通知
     */
    private fun sendLiveNotification() {
        LiveBroadcastUtils.sendLiveStartNotification(this, "精彩直播即将开始")
        Log.d("StartLiveActivity", "已发送直播预播提醒广播")
    }
    
    /**
     * 处理权限请求结果
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            NOTIFICATION_PERMISSION_REQUEST_CODE -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.d("StartLiveActivity", "通知权限已授权")
                    // 权限授权后发送通知
                    sendLiveNotification()
                } else {
                    Log.w("StartLiveActivity", "通知权限被拒绝，无法显示通知")
                    // 即使权限被拒绝，也尝试发送广播（某些设备可能仍能显示）
                    sendLiveNotification()
                }
            }
        }
    }

    /**
     * 初始化弹幕列表
     */
    private fun initDanmuList() {
        danmuAdapter = DanmuAdapter()
        binding.rvDanmuList.apply {
            adapter = danmuAdapter
            layoutManager = LinearLayoutManager(this@StartLiveActivity).apply {
                stackFromEnd = true // 从底部开始堆叠，新消息显示在底部
            }
        }
    }

    /**
     * 初始化点击事件
     */
    private fun initClickListeners() {
        // 发送弹幕按钮点击事件
        binding.btnSendDanmu.setOnClickListener {
            sendDanmu()
        }

        // 输入框回车发送
        binding.etDanmuInput.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEND) {
                sendDanmu()
                true
            } else {
                false
            }
        }

        // 礼物按钮点击事件
        binding.btnGift.setOnClickListener {
            toggleGiftList()
        }

        // 小黄车按钮点击事件
        binding.btnShoppingCart.setOnClickListener {
            Toast.makeText(this, "购物车功能开发中...", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 发送弹幕
     */
    private fun sendDanmu() {
        val message = binding.etDanmuInput.text.toString().trim()
        if (message.isNotEmpty()) {
            val danmu = DanmuMessage(
                username = currentUsername,
                message = message,
                messageType = DanmuMessage.MessageType.NORMAL
            )

            // 使用限制数量的方法，避免内存溢出
            danmuAdapter.addDanmu(danmu)

            // 滚动到最新消息
            binding.rvDanmuList.scrollToPosition(danmuAdapter.itemCount - 1)

            // 清空输入框
            binding.etDanmuInput.setText("")

            Log.d("StartLiveActivity", "发送弹幕: $message")
        } else {
            Toast.makeText(this, "请输入弹幕内容", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 切换礼物列表显示状态
     */
    private fun toggleGiftList() {
        binding.rvGiftList.visibility = if (binding.rvGiftList.visibility == View.VISIBLE) {
            View.GONE
        } else {
            View.VISIBLE
        }
    }

    /**
     * 添加示例弹幕
     */
    private fun addSampleDanmu() {
        val sampleDanmus = listOf(
            DanmuMessage(username = "观众1", message = "主播好棒！", messageType = DanmuMessage.MessageType.NORMAL),
            DanmuMessage(username = "观众2", message = "666666", messageType = DanmuMessage.MessageType.NORMAL),
            DanmuMessage(username = "观众3", message = "送给主播一个火箭🚀", messageType = DanmuMessage.MessageType.GIFT),
            DanmuMessage(username = "系统", message = "欢迎来到直播间", messageType = DanmuMessage.MessageType.SYSTEM)
        )

        danmuAdapter.addDanmuList(sampleDanmus)

        // 滚动到最新消息
        if (sampleDanmus.isNotEmpty()) {
            binding.rvDanmuList.scrollToPosition(danmuAdapter.itemCount - 1)
        }
    }
}